package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@RestController
@Slf4j
@RequestMapping("user")
public class UserController {

    @Resource
    private IUserService userService;
    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 昵称
     * @param password 密码
     * @param passwordRepeat 确认密码
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public AppResult regster (
                              @ApiParam("用户名") @RequestParam("username") @NonNull String username ,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname ,
                              @ApiParam("密码")@RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码")@RequestParam("passwordRepeat")@NonNull String passwordRepeat) {
        // 1. 接收用户请求
        // 2. 参数校验 不通过直接给用户返回错误响应 , 一般不在该层抛出异常
//        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname) ||
//        StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)) {
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
        // 校验密码是否一致
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 3. 准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        String salt = UUIDUtil.UUID_32();
        user.setSalt(salt);
        String encryptPassword = MD5Util.md5Salt(password,salt);
        user.setPassword(encryptPassword);
        userService.createUser(user);
        return AppResult.success(ResultCode.SUCCESS);
    }


    @PostMapping("/login")
    @ApiOperation("用户登录")
    public AppResult login (HttpServletRequest request
            , @ApiParam("用户名")@RequestParam("username")@NonNull String username
            ,@ApiParam("密码")@RequestParam("password") @NonNull String password) {
        User user = userService.login(username, password);
        // 用户处于删除状态 , 不能登录
        if (user == null || user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOTEXISTS);
        }

        // 设置session
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION , user);
        return AppResult.success(ResultCode.SUCCESS);
    }

    /**
     * 获取用户信息
     * @param request
     * @param id
     * @return
     */
    @GetMapping("/info")
    @ApiOperation("获取用户信息")
    public AppResult<User> getUserInfo (HttpServletRequest request
            , @ApiParam("用户id")@RequestParam(value = "id",required = false ) Long id) {
        User user = null ;
        if (id == null) {
            // 获取登录用户
            HttpSession session = request.getSession(false);
             // 用户没有登录 返回错误信息无权登录
             if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                 return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
             }
             user= (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            user = userService.selectById(id);
        }
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOTEXISTS);
        }
        return AppResult.success(user);
    }


    @ApiOperation("退出操作")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
            // 用户没有登录 , 直接退出就好

            return AppResult.success("退出成功");
        }
        log.info("退出成功");
        session.invalidate();// 删除session
        return AppResult.success("退出成功");
    }

    /**
     * 修改用户个人信息
     * @param request
     * @param username 用户名
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号码
     * @param remark 个人简介
     * @return
     */
    @PostMapping("/modifyInfo")
    @ApiOperation("更新用户个人信息")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @ApiParam("⽤⼾名") @RequestParam(value = "username",required = false) String username
            , @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname
            , @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender
            , @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email
            , @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum
            , @ApiParam("个⼈简介") @RequestParam(value = "remark",required = false) String remark) {
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            // 返回错误信息
            return AppResult.failed("请输⼊要修改的内容");
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getId() == null || user.getId() <= 0) {
            return AppResult.failed(ResultCode.FAILED_USER_NOTEXISTS);
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        userService.modifyInfo(updateUser);
        // 更新用户信息
        user = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success(updateUser);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request
            , @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword
            , @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword
            , @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 参数获取校验
        // 确认密码和密码一致
        // 原密码和数据库密码是否一致
        if (!newPassword.equals(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
//        String oldCipher = MD5Util.md5Salt(oldPassword,user.getSalt());
//        if (!oldCipher.equalsIgnoreCase(user.getPassword())) {
//            return AppResult.failed("原密码错误");
//        }
        userService.modifyPassword(user.getId(), newPassword , oldPassword);
        // 让session失效,用户重新登录
        if (session != null) {
            session.invalidate();
        }
        return AppResult.success(ResultCode.SUCCESS);
    }

}
